<?php
use app\assets\PublishAsset;
use yii\helpers\Html;
use yii\helpers\Url;

PublishAsset::register($this);
?>

<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title>发布商品页面</title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>

<style>

    .attrName{
        margin-top: 10px;
        font-size:15px;
    }

    .attributeSet{
        margin-left: -7px;
        margin-right: 10px;
        margin-bottom: 10px;
    }


    .categorySet{
        margin-left: -7px;
        margin-right: 10px;
        margin-bottom: 10px;
    }

    .sku_del{

        display: none;
        position: absolute;
        width: 20px;
        height: 20px;
        margin-left: -10px;
        margin-top: -6px;
        background-color: #00438A;
        background: url('https://d.weidian.com/images/items/icon_del3.png') no-repeat;

    }

    .category_del{

        display: none;
        position: absolute;
        width: 20px;
        height: 20px;
        margin-left: -10px;
        margin-top: -6px;
        background-color: #00438A;
        background: url('https://d.weidian.com/images/items/icon_del3.png') no-repeat;

    }

    .labelName{

        width: 80px;

    }

    .divName{
        margin-left: 80px;
        margin-top: -26px;

    }

    .datagrid-cell, .datagrid-cell-group, .datagrid-header-rownumber, .datagrid-cell-rownumber {
        overflow: visible !important;
    }
</style>

<div id="basicInfo">
        <form class="form-horizontal"  id="basicInfoForm">
        <fieldset>
            <div id="legend" class="">
                <legend class="">商品基本信息</legend>
            </div>

            <div class="form-group col-md-12">
                <label for="" class="control-label labelName">商品分类:</label>
                <div class="divName">
                    <div class="col-md-3 col-sm-3" >
                        <select name="" id="chooseCategorySelect" class="col-md-1 form-control" onchange="getValue(this)">
                        </select>
                    </div>
                    <div class="col-md-3 col-sm-3" >
                        <select name="" id="categorySelect" class="col-md-1 form-control" onchange="getCategory(this)">
                        </select>
                    </div>

                    <div class="col-md-2 col-sm-2" >
                         <p class="btn  btn-default" id="addCategoryBtn"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加</p>
                    </div>
                </div>
            </div>


            <div id="commodityDiv" >

                <div class="form-group col-md-12">
                    <label for="commodity_name" class="control-label labelName">商品名称:</label>
                    <div class="divName">
                        <div class="col-md-8 col-sm-8">
                            <input type="text" class="form-control " id="commodity_name" name="commodity_name" check-type="required" >
                        </div>
                    </div>
                </div>


                <div class="form-group col-md-12">
                    <label for="commodity_price" class="control-label labelName">商品价格:</label>
                    <div class="divName">
                        <div class="col-md-3 col-sm-3">
                            <input type="text" class="form-control " id="commodity_price" name="commodity_price" check-type="required positive" >
                        </div>
                    </div>
                </div>

                <div class="form-group col-md-12">
                    <label for="commodity_postage_template" class="control-label labelName">运费模板:</label>
                    <div class="divName" >
                        <div class="col-md-9 col-sm-9">
                            <span id="postageTemplate"></span>
                            <span id="postageTemplateErrorMessage" style="display: none">请输入内容</span>
                            <p class="btn btn-primary"  id="choosePostageTemplateBtn">设定运费模板</p>
                        </div>
                    </div>
                </div>

                <div class="form-group col-md-12">
                    <label for="commodity_price" class="control-label labelName">商品规格:</label>
                    <div class="divName" >
                        <div class="col-md-9 col-sm-9">
                            <div id="rankDiv">
                            </div>
                            <p class="btn btn-primary"  id="addRank">设定多级规格</p>
                        </div>
                    </div>
                </div>
                <div class="form-group col-md-12">
                    <label for="stock_num" class="control-label labelName">商品总数:</label>
                    <div class="divName">
                        <div class="col-md-3 col-sm-3">
                            <input type="text" class="form-control " id="stock_num" name="stock_num" check-type="required number" >
                        </div>
                    </div>
                </div>
                <div class="form-group col-md-12">
                    <label for="commodity_code" class="control-label labelName">商品条码:</label>
                    <div class="divName">
                        <div class="col-md-8 col-sm-8">
                            <input type="text" class="form-control " id="commodity_code" name="commodity_code"  >
                        </div>
                    </div>
                </div>
                <div class="form-group col-md-12">
                    <label  class="control-label labelName">橱窗推荐:</label>
                    <div class="divName">
                        <div class="col-md-8 col-sm-8">
                            <input type="checkbox" id="is_hot" style="width: 15px; vertical-align:middle; margin:auto;height:30px; padding:0;">
                        </div>
                    </div>
                </div>
                <div class="form-group col-md-12">
                    <label for="commodity_price" class="control-label labelName">商品图片(拖动交换顺序):</label>
                    <div class="divName" >
                        <div class="col-md-10 col-sm-10">
                            <div id="uploadImg" ></div>
                        </div>
                    </div>
                </div>
                <div class="form-group col-md-9">
                    <label  class="control-label labelName">商品描述:</label>

                    <div style="width:400px;height:500px;margin: 0 auto;">

                        <div class="publish-article-content" style="text-align: left">
                            <div class="title-tips">商品详情<a href="#" style="float: right">预览</a></div>
                            <input type="hidden" id="target">
                            <div class="article-content" id="content">
                            </div>
                            <div class="footer-btn g-image-upload-box">
                                <div class="upload-button">
                                    <span class="upload"><i class="upload-img"></i>插入图片</span>
                                    <input class="input-file" id="imageUpload" type="file" name="fileInput" capture="camera" accept="image/*" style="position:absolute;left:0;opacity:0;width:100%;">
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="divName" style="display: none">
                        <div class="col-md-10 col-sm-10">
                            <script type="text/plain" id="myEditor" style="width:100%;height:240px;">
                            </script>
                        </div>
                    </div>
                </div>

                <div class="form-group col-md-9">
                    <center>
                        <p id="publishBtn" class="btn btn-primary publishBtn">发布商品</p>
                        <p id="saveBtn" class="btn btn-default publishBtn">放入仓库</p>
                    </center>
                </div>

                                    </div>
                                </fieldset>
                            </form>
                        </div>

                        <!-- 添加的分类Modal 提示框-->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >添加分类信息</h4>
            </div>
            <div id="addForm">
                <div class="modal-body">
                    <div class="form-group">
                        <div>
                            <select name="" id="modalChooseCategorySelect" class="form-control" >
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="category_name_input" class="control-label">分类名称:</label>
                        <input type="text" class="form-control" id="category_name_input" name="category_name_input" check-type="required" >
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-primary"  id="addBtn">确定添加</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 选择运费模板Modal 提示框-->
<div class="modal fade" id="choosePostageTemplateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >选择运费模板</h4>
            </div>
            <div id="postageTempalteForm">
                <div class="modal-body" >
                    <div class="form-group">
                        <select id="postageTemplates" class="form-control" >
                        </select>
                        <div>
                            <div id="postageTemplateDetail">
                                <table id="postageTemplateDetailTable">
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-primary"  id="surePostageTemplateBtn">确定选择</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 选择规格Modal 提示框-->
<div class="modal fade" id="rankModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >选择多级规格</h4>
            </div>
            <div id="rankForm">
                <div class="modal-body" >
                    <div class="form-group">
                        <div class="categorySetDiv" >

                        </div>

                        <div class="input-group col-md-5 col-sm-5" style="padding-top: 15px;padding-bottom: 20px">
                            <input type="text" class="form-control categoryInput" placeholder="请输入商品属性">
                            <span class="input-group-btn">
                                <button class="btn btn-default newCategoryBtn" type="button">新建</button>
                            </span>
                        </div>
                        <span style="display: none" id="category_id_span"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-primary"  id="sureCategoryBtn">确定添加</button>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- 删除的Modal 提示框-->
<div class="modal fade" id="removeAttrModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >删除操作</h4>
            </div>
                <div class="modal-body" >
                    <input type="text" name="" id="attr_id_input" style="display: none">

                    <p style="color: red">是否确定删除，一旦删除后不可恢复</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary"  id="removeAttrBtn">确定删除</button>
                </div>
        </div>
    </div>
</div>

<div class="modal fade" id="removeAttrOptModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >删除操作</h4>
            </div>
            <div class="modal-body" >
                <input type="text" name="" id="attr_opt_id_input" style="display: none">

                <p style="color: red">是否确定删除，一旦删除后不可恢复</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary"  id="removeAttrOptBtn">确定删除</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">

    UM.getEditor('myEditor').setContent("",false,false);

    //加载一级二级目录
    $.ajax({
        url:"first-category-list",
        dataType: "json",
        success: function (data) {
            $.each(data,function(){
                $('#chooseCategorySelect').append('<option value='+this['category_id']+'>'+this['category_name']+'</option>');
                $('#modalChooseCategorySelect').append('<option value='+this['category_id']+'>'+this['category_name']+'</option>');
            });
        }
    });

    //加载二级目录
    $.get(
        "second-category-list",
        {pid:1},
        function (data,status){
            if (status) {
                $.each(data, function () {
                    $('#categorySelect').append('<option value=' + this['category_id'] + '>' + this['category_name'] + '</option>');
                });

                $('#category_id_span').html(data[0]['category_id']);

                initCategory(data[0]['category_id']);

            }else{
                alert('分类目录加载失败,请刷新');
            }
        },
        "json"
    );

    //初始化默认分类下的属性
    function initCategory(category_id){
        //加载属性可选择项目
        $.ajax({
            url: "get-attr-list-by-category-id",
            data:{"category_id":category_id},
            dataType: "json",
            success: function (data) {
                $.each(data,function(){
                    $('.categorySetDiv').append('<p class="label categorySet"> <span class="btn btn-default categoryBtn" id=attr_id'+this['attr_id']+'>'+this['attr_name']+'</span> <i class="category_del"></i> </p>');
                });
            }
        });

    }


    //第一级分类取值，获取相应的商品规格属性
    function getValue(obj) {

        $("#categorySelect").empty();

        $.get(
            "second-category-list",
            {pid:obj.options[obj.selectedIndex].value},
            function (data,status){
                if (status) {
                    $.each(data, function () {
                        $('#categorySelect').append('<option value=' + this['category_id'] + '>' + this['category_name'] + '</option>');
                    });
                    console.log('二级分类加载成功');

                }else{
                    alert('网络错误,请重试');
                }
            },
            "json"
        );

    }

    //第二级分类取值，获取相应的商品规格属性
    function getCategory(obj) {
        console.log(obj.options[obj.selectedIndex].text);

        //清空属性表
        $('#rankDiv').children().remove();
        $('.categorySetDiv').children().remove();

        $category_id = $("#categorySelect").val();

        $('#category_id_span').html($category_id);

        //加载属性可选择项目
        $.ajax({
            url: "get-attr-list-by-category-id",
            data:{"category_id":$category_id},
            dataType: "json",
            success: function (data) {
                $.each(data,function(){
                    console.log(this['attr_name']+this['attr_id']);
                    $('.categorySetDiv').append('<p class="label categorySet"> <span class="btn btn-default categoryBtn" id=attr_id'+this['attr_id']+'>'+this['attr_name']+'</span> <i class="category_del"></i> </p>');
                });
            }
        });

    }

    //点击添加分类的按钮事件弹出框
    $('#addCategoryBtn').click(function() {
        $('#addModal').modal();
    });

    //确定添加分类按钮
    $('#addBtn').click(function() {

        //正则提示写法
        if ($("#addForm").valid()==false){
            alert('填写信息有误,请检查');
            return false;
        }

        var value = $("#modalChooseCategorySelect option:selected").val();

        $.get(
            "add-second-category",
            {pid:value,category_name:$('#category_name_input').val()},
            function (data,status){
                if (status) {


                    if(data==='0'){
                        alert('填写信息有误,请检查');
                    }else{
                        $("#chooseCategorySelect").val(value);
                        $("#categorySelect").empty();

                        $.each(data, function () {
                            $('#categorySelect').append('<option value=' + this['category_id'] + '>' + this['category_name'] + '</option>');
                        });
                        $("#categorySelect option:last").attr('selected','selected');
                        console.log('新增成功');
                    }
                }else{
                    alert('网络错误,请重试');

                }

                $('#addModal').modal('hide');
                $('#category_name_input').val("");
            },
            "json"
        );

    });


    //实例化富文本编辑器
    var um = UM.getEditor('myEditor');

    var pic_url_arr=[];

    //上传图片的回调操作
    $('#uploadImg').diyUpload({
//        url:"vendor/fileupload.php",
        url:<?php  $currentStr = url::toRoute('/vendor/fileupload.php',true); echo '"'.$currentStr.'"' ;?>,
        success:function( data ) {
            pic_url_arr.push(data);
            console.log(data);
        },
        error:function( err ) {
            console.info( err );
        }
    });

    //正则的样式
    $(function() {
        //1. 正则逻辑样式
        $("#addForm").validation({icon: true, reqmark: false});
        $("#basicInfoForm").validation({icon: true, reqmark: false});
    });

    $(function(){

        //点击显示模态框
        $('#addRank').click(function() {
            $('#rankModal').modal();

        });

        //点击显示模态框
        $('#choosePostageTemplateBtn').click(function() {
            //加载模板
            $.ajax({
                url:"../postage-template/get-all",
                dataType: "json",
                async: false,
                success: function (data) {
                    $('#postageTemplates').empty();
                    $.each(data,function(){
                        $('#postageTemplates').append('<option value="'+this['id']+'" data-default-unit-price='
                            + this['default_unit_price'] +'>'+this['name']+'</option>');
                    });
                }
            });

            //显示模态框
            $('#choosePostageTemplateModal').modal();
            
            //显示表格

            setTimeout(function() {
                $('#postageTemplateDetailTable').datagrid({
                    title:'模板详情',
                    iconCls:'icon-edit',
                    width:$('#postageTemplateToolbox').outerWidth(true),
                    height:250,
                    singleSelect:true,
                    showFooter:true,
                    idField:'province_name',
                    url:'../postage-template/get-detail',
                    columns:[[
                        {field:'province_name',title:'省份',align:'center',
                            width:$('#postageTemplates').width() / 2},
                        {field:'unit_price',title:'单价',align:'center',editor:{type:'numberbox',options:{precision:2}},
                            width:$('#postageTemplates').width() / 2},
                    ]],
                    onEndEdit:function(index,row){
                        var select = $('.datagrid-row-selected').find('.filter-option.pull-left');
                        if (select.length > 0) {
                            row.province_name = select.text();
                        }
                    },
                    onBeforeEdit:function(index,row){
                        row.editing = true;
                        $(this).datagrid('refreshRow', index);
                    },
                    onAfterEdit:function(index,row){
                        if (row.province_name == null || row.province_name == "") {
                            alert('请选择省份')
                            $('#postageTemplateDetailTable').datagrid('beginEdit', index);
                        } else {
                            row.editing = false;
                            $(this).datagrid('refreshRow', index);
                        }
                    },
                    onBeginEdit:function(index,row){
                        $('.selectpicker').selectpicker('render');
                    },
                    onCancelEdit:function(index,row){
                        if (row.province_name == null || row.province_name == "") {
                            alert('请选择省份')
                            $('#postageTemplateDetailTable').datagrid('beginEdit', index);
                        } else {
                            row.editing = false;
                            $(this).datagrid('refreshRow', index);
                        }
                    },
                    onLoadSuccess:function(data){
                        var unit_price = $($('#postageTemplates')[0].options[$('#postageTemplates')[0].selectedIndex]).attr('data-default-unit-price');
                        if (unit_price) {
                            insert({"province_name":"全国","unit_price":unit_price});
                            $('#postageTemplateDetailTable').datagrid('endEdit', $('#postageTemplateDetailTable').datagrid('getRowIndex',
                                $('#postageTemplateDetailTable').datagrid('getSelected')));
                        }
                    }
                });
                reload();
            }, 300);
        });

        $('body').on('change', '#postageTemplates', function(){
            reload();
        });

        //点击选择运费模板按钮
        $("body").on('click','#surePostageTemplateBtn',function(){
            if ($('#postageTemplateDetailTable').datagrid('getChanges').length > 0) {
                alert('请保存修改内容')
            } else {
                $('#postageTemplate').attr('value', $("#postageTemplates").val());
                $('#postageTemplate').text($("#postageTemplates")[0].options[$("#postageTemplates")[0].selectedIndex].text);
                $('#choosePostageTemplateModal').modal('hide');
            }
        });

        //删除图标显示hover事件
        $("body").on('mouseover mouseout','.attributeSet',function(e){
            e = e||event;
            if(e.type == "mouseover"){
                //鼠标悬浮
                $(this).children("i").css("display","inline");
            }else if(e.type == "mouseout"){
                //鼠标离开
                $(this).children("i").css("display","none");

            }
        });

        //删除图标显示hover事件
        $("body").on('mouseover mouseout','.categorySet',function(e){
            if(e.type == "mouseover"){
                //鼠标悬浮
                $(this).children("i").css("display","inline");
            }else if(e.type == "mouseout"){
                //鼠标离开
                $(this).children("i").css("display","none");

            }
        });


        //新建分类中属性添加按钮点击事件
        $('body').on('click','.newCategoryBtn',function(){
            //为空不操作
            if(!$(".categoryInput").val()){
                return;
            }

            var attr_name = $(".categoryInput").val();

            //加载属性可选择项目
            $.ajax({
                url: "add-attr",
                data:{"category_id":$('#category_id_span').html(),"attr_name":attr_name},
                dataType: "json",
                success: function (data) {
                    if(data==='0'){
                        alert('填写信息有误,请检查');
                    }else {
                        $('.categorySetDiv').append('<p class="label categorySet"> <span class="btn btn-default categoryBtn" id=attr_id' + data + '>' + attr_name + '</span> <i class="category_del"></i> </p>');
                    }
                }
            });
            $(".categoryInput").val('');

        });

        //新建分类中属性添加按钮点击事件
        $('body').on('click','.newAttributeBtn',function() {
            //为空不操作
            if(!$(this).parent().prev().val()){
                return;
            }


            var attr_opt_name = $(this).parent().prev().val();

            $attr_id = $(this).parent().parent().prev().prev().attr('ID');
            var attr_id=$attr_id.substr(9);

            $that=$(this).parent().parent().prev();


            //加载属性可选择项目
            $.ajax({
                url: "add-attr-opt",
                data:{"attr_id":attr_id,"attr_opt_name":attr_opt_name},
                dataType: "json",
                success: function (data) {
                    if(data==='0'){
                        alert('填写信息有误,请检查');
                    }else {
                        $that.append('<p class="label  attributeSet"> <span class="btn btn-default attributeBtn" id=attr_opt_id'+data+'>'+attr_opt_name +'</span> <i class="sku_del" ></i> </p>');
                    }
                }
            });

//            $(this).parent().parent().prev().append('<p class="label attributeSet">'+ '<span class="btn btn-default attributeBtn">'+$(this).parent().prev().val()+'</span>'+ '<i class="sku_del"></i>'+'</p>');
            //清空输入框原有内容
            $(".attributeInput").val('');

        });


        //删除按钮点击事件
        $("body").on('click','.category_del',function(){
            $('#attr_opt_id_input').val('');
            $('#removeAttrModal').modal();
            $attr_id=$(this).prev().attr('ID');
            $('#attr_id_input').val($attr_id);



        });

        //删除属性按钮点击事件
        $("body").on('click','.sku_del',function(){
            $('#attr_id_input').val('');
            $('#removeAttrOptModal').modal();
            $attr_opt_id=$(this).prev().attr('ID');
            $('#attr_opt_id_input').val($attr_opt_id);

        });

        $('#removeAttrOptBtn').click(function(){


            if($('#attr_opt_id_input').val()){
                $attr_opt_id=$('#attr_opt_id_input').val();
                var attr_opt_id=$attr_opt_id.substr(11);
                //删除属性操作选择项目
                console.log(attr_opt_id);

                $.ajax({
                    url: "remove-attr-opt",
                    data:{"attr_opt_id":attr_opt_id},
                    dataType: "json",
                    success: function () {


                    }
                });

                //删除父元素 需要调接口
                $id = '#'+$attr_opt_id;
                $($id).parent().remove();
                $('#removeAttrOptModal').modal('hide');
                $('#attr_opt_id_input').val('');

            }


        });

        $('#removeAttrBtn').click(function() {


            if ($('#attr_id_input').val()) {
                $attr_id = $('#attr_id_input').val();
                var attr_id = $attr_id.substr(7);
                //删除属性操作选择项目
                $.ajax({
                    url: "remove-attr",
                    data: {"attr_id": attr_id},
                    dataType: "json",
                    success: function () {


                    }
                });

                //删除父元素 需要调接口
                $id1 = '#' + $attr_id;
                $($id1).parent().remove();
                console.log($id1);
                $('#removeAttrModal').modal('hide');
                $('#attr_id_input').val('');

            }

        });

        //点击属性按钮高亮或者熄灭
        $("body").on('click','.attributeBtn',function(){
            if($(this).hasClass('btn-default')){
                $(this).addClass('btn-info');
                $(this).removeClass('btn-default');
            }else{
                $(this).addClass('btn-default');
                $(this).removeClass('btn-info');
            }
        });

        $("body").on('click','.categoryBtn',function(){
            if($(this).hasClass('btn-default')){
                $(this).addClass('btn-info');
                $(this).removeClass('btn-default');
            }else{
                $(this).addClass('btn-default');
                $(this).removeClass('btn-info');
            }
        });



        //点击选择属性按钮
        $("body").on('click','#sureCategoryBtn',function(){

            //遍历拿到已选的规格数组
            var arr=[];
            $('#rankDiv').children('div').children('p').each(function(){

                arr.push($(this).text());
                console.log(arr);

            });

            //规格遍历处理
            $('.categorySetDiv').children('p').children('span').each(function(){

                if($(this).hasClass('btn-default')){

                    //删除规格
                    if($.inArray($(this).text(), arr)==-1){

                        console.log('没有选择的'+$(this).text()+'不做删除处理');

                    }else {
                        var attr_name = $(this).text();


                        $('.attrName').each(function(){

                            if($(this).text()==attr_name){

                                $(this).parent().remove();
                            }

                        });

                        console.log('移除'+$(this).text());
                    }



                }else if($(this).hasClass('btn-info')){


                    //新增规格
                    if($.inArray($(this).text(), arr)==-1){


                        var attr_name = $(this).text();
                        $attr_id = $(this).attr('ID');
                        var attr_id=$attr_id.substr(7);

                        //加载属性可选择项目
                        $.ajax({
                            url: "get-attr-opt-list-by-attr-id",
                            data:{"attr_id":attr_id},
                            dataType: "json",
                            success: function (data) {
                                var strl = '<div><p class="attrName" id=attr_id_p'+attr_id+'>'+attr_name+'</p><div class="attributeSetDiv col-sm-12 col-md-12" style="margin-left: -15px;">';
                                console.log(data);
                                $.each(data, function () {
                                    var str = '<p class="label  attributeSet"> <span class="btn btn-default attributeBtn" id=attr_opt_id'+this['attr_opt_id']+'>'+this['attr_opt_name'] +'</span> <i class="sku_del" ></i> </p>';
                                    strl+=str;
                                    console.log(this['attr_opt_name']+'---->'+str);
                                });
                                $('#rankDiv').append(strl+'</div> <div class="input-group col-md-3 col-sm-3" style="padding-top: 15px;padding-bottom: 20px"> <input type="text" class="form-control attributeInput" placeholder="请输入商品属性" > <span class="input-group-btn"> <button class="btn btn-default newAttributeBtn" type="button" >新建</button> </span></div> </div>');
                            }
                        });
                        console.log('新增'+$(this).text());
                    }else{
                        console.log('已经存在'+$(this).text()+'不做新增处理');
                    }
                }
            });
            $('#rankModal').modal('hide');
        });
    });

    function getRowIndex(target){
        var tr = $(target).closest('tr.datagrid-row');
        return parseInt(tr.attr('datagrid-row-index'));
    }
    function editrow(target){
        $('#postageTemplateDetailTable').datagrid('beginEdit', getRowIndex(target));
    }
    function deleterow(target){
        $.messager.confirm('Confirm','Are you sure?',function(r){
            if (r){
                $('#postageTemplateDetailTable').datagrid('deleteRow', getRowIndex(target));
            }
        });
    }
    function saverow(target){
        $('#postageTemplateDetailTable').datagrid('endEdit', getRowIndex(target));
    }
    function cancelrow(target){
        $('#postageTemplateDetailTable').datagrid('cancelEdit', getRowIndex(target));
    }
    function insert(target){
        index = 0;
        if (!target) {
            target = {
                "province_name" : "",
                "unit_price": "0.00"
            };
            index = $('#postageTemplateDetailTable').datagrid('getRows').length;
        }
        $('#postageTemplateDetailTable').datagrid('insertRow', {
            index:index,
            row:target
        });
        $('#postageTemplateDetailTable').datagrid('selectRow',index);
        $('#postageTemplateDetailTable').datagrid('beginEdit',index);
    }
    function reload(){
        $('#postageTemplateDetailTable').datagrid('options').queryParams = {
            "template_id" :$("#postageTemplates").val()
        };
        $('#postageTemplateDetailTable').datagrid('reload');
    }

    //点击发布商品
    $('.publishBtn').click(function(){


        //正则提示写法
//        if ($("#basicInfoForm").valid()==false){
//            alert('填写信息有误,请检查');
//            return false;
//        }
//
//        if ($('#commodity_price').val()<=0){
//            alert('商品价格必须大于0');
//            return false;
//        }
//
//        if ($('#postageTemplate').attr('value') == null || $('#postageTemplate').attr('value') == '') {
//            alert('填写信息有误,请检查');
//            $('#postageTemplateErrorMessage').show();
//            return false;
//        } else {
//            $('#postageTemplateErrorMessage').hide();
//        }

        if(document.getElementById("is_hot").checked==true){
            var is_hot =1;
        }else{
            var is_hot =0;
        }


        if($(this).text()=='发布商品'){
            var is_sale =1;
        }else{
            var is_sale =0;
        }


        //遍历拿到已选的规格数组
        var arr=[];
        var flag = true;
        $('#rankDiv').children('div').children('p').each(function(){
            var arr1=[];
            arr1.push($(this).attr('ID').substr(9));
            var arr2=[];
            $(this).next().children('p').children('span').each(function(){

                if($(this).hasClass('btn-info')){
                    arr2.push($(this).attr('ID').substr(11));
                    flag = false;
                };


            });
            arr1.push(arr2);
            arr.push(arr1);
        });

        if(flag){
            alert('商品属性未设置，请设置');
            return false;
        }

        var first_category = $("#chooseCategorySelect option:selected").val();//一级分类category_id
        var second_category = $("#categorySelect option:selected").val();//二级分类category_id

        var store_id = 1;//假数据

        var price = $('#commodity_price').val();
        var stock_num = $('#stock_num').val();
        var commodity_name = $('#commodity_name').val();
        var pro_id =$('#commodity_code').val();
        var pic_url = pic_url_arr[0];
        var banner_url = JSON.stringify(pic_url_arr);
        var content = getAllHtml();//文本详情
        var contentTrue = getPlainTxt();//内容

        var attr_opt_id = JSON.stringify(arr);

        if(!pic_url){
            alert('请上传商品主图(最少一张)');
            return false;
        }

        if(!contentTrue){
            alert('请编辑商品描述');
            return false;
        }

        //加载属性可选择项目
        $.ajax({
            type:'POST',
            data:{
                "store_id":store_id,
                "price":price,
                "pic_url":pic_url,
                "banner_url":banner_url,
                "is_hot":is_hot,
                "commodity_name":commodity_name,
                "content":content,
                "content_true":contentTrue,
                "first_category":first_category,
                "second_category":second_category,
                "attr_opt_id":attr_opt_id,
                "pro_id":pro_id,
                "is_sale":is_sale,
                "stock_num":stock_num,
                "postage_template_id":$('#postageTemplate').attr('value')
            },
            dataType: "json",
            url: "publish",
            success: function (data) {

                if(data=='0'){

                }else{
                    alert('发布成功');
                    window.location.reload();

                }

            }
        });



    });

    //富文本获取所有Html
    function getAllHtml() {
        return UM.getEditor('myEditor').getAllHtml();
    }

    //获取输入内容
    function getContent() {
        return UM.getEditor('myEditor').getContent();
    }
    //使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容
    function getPlainTxt() {

        return UM.getEditor('myEditor').getPlainTxt();

    }

    function allowDrop(ev)
    {
        ev.preventDefault();
    }

    function drag(ev)
    {
        ev.dataTransfer.setData("Text",ev.target.id);
    }

    function drop(ev) {
        ev.preventDefault();
        var originId = ev.dataTransfer.getData("Text");
        var originIndex = originId.substr(originId.length - 1);
        var origin = document.getElementById(originId);
        var originSrc = $(origin).attr('src');
        var targetId = ev.target.id;
        var targetIndex = targetId.substr(targetId.length - 1)
        var target = ev.target;
        var targetSrc = $(target).attr('src');
        var maxIndex = originIndex > targetIndex ? originIndex : targetIndex;
        var minIndex = originIndex < targetIndex ? originIndex : targetIndex;
        if (pic_url_arr.length > minIndex && pic_url_arr.length <=   maxIndex) {
            alert('不能交换已上传图片和未上传图片');
        }
        else {
            $(target).attr('src', originSrc);
            $(origin).attr('src', targetSrc);
        }
        if (pic_url_arr.length > maxIndex) {
            var swapItem = pic_url_arr[originIndex];
            pic_url_arr[originIndex] = pic_url_arr[targetIndex];
            pic_url_arr[targetIndex] = swapItem;
        }
    }


</script>

<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>